var zTree, rMenu,
	IDMark_Switch = "_switch",
	IDMark_Icon = "_ico",
	IDMark_Span = "_span",
	IDMark_Input = "_input",
	IDMark_Check = "_check",
	IDMark_Edit = "_edit",
	IDMark_Remove = "_remove",
	IDMark_Ul = "_ul",
	IDMark_A = "_a";

var setting1 = {
	edit: {
		enable: true,
		showRemoveBtn: false,
		showRenameBtn: false
	},
	data: {
		key: {
			title: "" //默认name名称

		},
		simpleData: {
			enable: true
		}
	},
	callback: {
		beforeDrag: beforeDrag,
		onDrop: zTreeOnDrop,
		onClick: zTreeOnClick
	},
	check: {
		enable: true
	}
};

var setting2 = '';
if(!$("#treeDemo").hasClass("nochoice")) {
	setting2 = {
		view: {
			showIcon: false, //显示图标
			showTitle: true, //默认name名称
			selectedMulti: false,
			addDiyDom: addDiyDom, //特殊样式
			removeHoverDom: removeHoverDom, //移除鼠标上移效果
			addHoverDom: addHoverDom
		}
	};
} else {
	setting2 = {
		view: {
			showIcon: false, //显示图标
			showTitle: true, //默认name名称
			selectedMulti: false,
			addDiyDom: addDiyDom //特殊样式
		},
	}
};

//特殊样式
function addDiyDom(treeId, treeNode) {
	var spaceWidth = 5;
	var switchObj = $("#" + treeNode.tId + "_switch"),
		icoObj = $("#" + treeNode.tId + "_ico");
	switchObj.remove();
	icoObj.before(switchObj);

	if(treeNode.level > 1) {
		var spaceStr = "<span style='display: inline-block;width:" + (spaceWidth * treeNode.level) + "px'></span>";
		switchObj.before(spaceStr);
	}
}

//点击刷新
var lastClick_ = null;

function zTreeOnClick(event, treeId, treeNode) {
	console.log(treeNode)
	if(event.target.className === "treeSel" || event.target.nodeName === "I") {
		//顶层节点没有权限
		if(treeNode.parentName != null) {
			$("#m_addroot").removeClass("nochoicethis");
		} else {
			$("#m_addroot").addClass("nochoicethis");
		}
		//判断最上面或最下面的节点，不能上移或者下移
		if(treeNode.isFirstNode && treeNode.isLastNode) {
			$("#m_down").addClass("nochoicethis");
			$("#m_up").addClass("nochoicethis");
		} else if(treeNode.isLastNode) {
			$("#m_down").addClass("nochoicethis");
			$("#m_up").removeClass("nochoicethis");
		} else if(treeNode.isFirstNode) {
			$("#m_down").removeClass("nochoicethis");
			$("#m_up").addClass("nochoicethis");
		} else {
			$("#m_down").removeClass("nochoicethis");
			$("#m_up").removeClass("nochoicethis");
		}
		showRMenu($("#diyBtn_" + treeNode.id), event.clientX, event.clientY);
	}
	//判断是否点击同一元素
	if(lastClick_ === treeNode.tId) {
		return false;
	}
	console.log(treeNode.tId + ", " + treeNode.name);

	lastClick_ = treeNode.tId;
	table_.resetPaginationParams();
	table_.orgCode = treeNode.id;
	table_.orgName = treeNode.name;
	table_.firstLoad_ = false;
	table_.status = "";
	table_.searchValue = "";
	table_.getData();
}

//用于捕获节点拖拽操作结束的事件回调函数
function zTreeOnDrop(event, treeId, treeNodes, targetNode, moveType) {
	alert(treeNodes.length + "," + (targetNode ? (targetNode.tId + ", " + targetNode.name) : "isRoot"));
};

//禁止拖曳
function beforeDrag(treeId, treeNodes) {
	return false;
}

function focusKey(e) {
	var target = $(e.target);
	if(target.hasClass("empty")) {
		target.removeClass("empty");
	}
}

function blurKey(e) {
	var target = $(e.target);
	if(target.val() === "") {
		target.addClass("empty");
	}
}
var lastValue = "",
	nodeList = [];
var key, curMenu, NodeSettingObj;
//初始化左侧树
function VanyBaseTree(el, urlordata, NodeSetting) {
	var promise_ = $.ajax({
		url: urlordata,
		method: "GET",
		dataType: "json",
		cache: false,
		success: function(data) {
			var treeObj = $("#" + el);
			NodeSettingObj = NodeSetting;
			console.log(data)
			$.fn.zTree.init(treeObj, NodeSettingObj, data.resultData);
			zTree = $.fn.zTree.getZTreeObj(el);
			try {
				//默认展开第一节点
				var curMenu = zTree.getNodes()[0];
				zTree.selectNode(curMenu);
				//节点展开
				for(var i = 0; i < zTree.getNodes().length; i++) { //设置节点展开
					zTree.expandNode(zTree.getNodes()[i], true, false, true);
				}
			} catch(e) {
				console.log("1")
			}
			//			treeObj.hover(function() {
			//				if(!treeObj.hasClass("showIcon")) {
			//					treeObj.addClass("showIcon");
			//				}
			//			}, function() {
			//				treeObj.removeClass("showIcon");
			//			});
			rMenu = $("#rMenu");
			key = $("#key");
			key.bind("focus", focusKey)
				.bind("blur", blurKey)
				.bind("propertychange", searchNode)
				.bind("input", searchNode);
		},
		error: function() {},
	});
	return promise_;
}

var treeNodeCur, treeIdCur;
//鼠标上移在树上效果
function addHoverDom(treeId, treeNode) {
	if($("#" + treeId).hasClass("nochoice")) {
		return;
	}
	treeNodeCur = '';
	treeNodeCur = treeNode;
	treeIdCur = '';
	treeIdCur = treeId;
	if(treeNodeCur.parentNode && treeNodeCur.parentNode.id != 1) return;
	var aObj = $("#" + treeNodeCur.tId + IDMark_A).find(".node_name");
	if($("#diyBtn_" + treeNodeCur.id).length > 0) return;
	$(this).closest("a").addClass("gray");
	var editStr = "<div class='treeSel' id='diyBtn_" + treeNodeCur.id + "'>" +
		"<i class='iconfont icon-xia'></i>" +
		"</div>";
	aObj.append(editStr);
	var btn = $("#diyBtn_" + treeNodeCur.id);
	if(btn) btn.bind("change", function() {
		alert("diy Select value=" + btn.attr("value") + " for " + treeNodeCur.name);
	});
}
////显示弹框
//var myTimeout = null;
//显示弹框坐标
function showRMenu(thisId, x, y) {
    thisId.find("i").removeClass("icon-xia").addClass("icon-shang");
    if ((thisId.offset().top + rMenu.height()) > $(window).height()) {
		console.log(thisId.offset().top);
        rMenu.css({
            "top": thisId.offset().top - rMenu.height() - 20 - 210 + "px" //当前位置top值 - 悬浮框本身高度 -到头部的距离20-头部菜单以及面包屑高度
        })
    } else {
        rMenu.css({
            "top": thisId.offset().top + 28 - 210 + "px" //当前位置top值+到底部的距离20-头部菜单以及面包屑高度
        })
    }
    rMenu.css({
        "left": thisId.offset().left - $(".left-main").width() - rMenu.width() - 4 + "px",
        "visibility": "visible"
    })
    $("body").bind("mousedown", onBodyMouseDown);
}

//隐藏弹框
function hideRMenu() {
	$("#treeDemo a").removeClass("gray");
	$(".treeSel").find("i").removeClass("icon-shang").addClass("icon-xia");
	rMenu.removeAttr("style"); //ie,ff均支持
	$("body").unbind("mousedown", onBodyMouseDown);
}
//鼠标点击其他区域，弹框隐藏
function onBodyMouseDown(event) {
	if(!(event.target.id == "rMenu" || $(event.target).parents("#rMenu").length > 0)) {
		$(".treeSel").find("i").removeClass("icon-shang").addClass("icon-xia");
		rMenu.removeAttr("style"); //ie,ff均支持
	}
}
//鼠标移动时，下拉按钮消失
function removeHoverDom(treeId, treeNode) {
	$("#diyBtn_" + treeNode.id).unbind().remove();
}

//搜索功能
function searchNode(e) {
	var target = $(e.target);
	var value = target.val();
	/*var value = $.trim(key.get(0).value);*/
	var keyTypeName;
	if("undefined" == typeof NodeSettingObj.data.key.name) {
		keyTypeName = "name";
	} else {
		keyTypeName = NodeSettingObj.data.key.name;
	}
	/*if(key.hasClass("empty")) {
		value = "";
	}*/
	if(target.hasClass("empty")) {
		value = "";
	}
	if(lastValue === value) return;
	lastValue = value;
	if(value === "") {
		zTree.showNodes(zTree.transformToArray(zTree.getNodes()));
		return;
	}

	nodeList = zTree.getNodesByParamFuzzy(keyTypeName, value);
	nodeList = zTree.transformToArray(nodeList);
	updateNodes(true);

}

/**不查询父级*/
for(var x = 0; x < nodeList.length; x++) {
	if(nodeList[x].isParent) {
		nodeList.splice(x--, 1);
	}
}
//根据搜索框更新树
function updateNodes(highlight) {
	var allNode = zTree.transformToArray(zTree.getNodes());
	zTree.hideNodes(allNode);
	for(var n in nodeList) {
		findParent(zTree, nodeList[n]);
	}
	zTree.showNodes(nodeList);
}

function findParent(zTree, node) {
	zTree.expandNode(node, true, false, false);
	var pNode = node.getParentNode();
	if(pNode != null) {
		nodeList.push(pNode);
		findParent(zTree, pNode);
	}

}